//
//  KAInputPwdVC.swift
//  kano
//
//  Created by Sophia on 2024/8/20.
//

import UIKit
import RxCocoa
import RxSwift

class KAInputPwdVC: KABaseVC {
    
    var codeToken: String = ""
    var logoutStatus: Int = 0
    var pwd: String = ""
    var secondLogin: Int = 0
    var captchaCode: String = ""
    var captchaId: String = ""
    
    private let disposeBag = DisposeBag()
    
    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = UIColor.white
        var_cornerView.layer.cornerRadius = kscale(30)
        var_cornerView.layer.masksToBounds = true
        var_cornerView.frame = CGRectMake(kscale(20), UIDevice.ka_fullNavHeight+kscale(40), var_screenWidth-kscale(40), kscale(330))
        return var_cornerView
    }()
    
    lazy var var_titleLabel: UILabel = {
        let var_titleLabel = UILabel()
        var_titleLabel.x = kscale(20)
        var_titleLabel.y = kscale(32)
        var_titleLabel.width = var_cornerView.width-kscale(40)
        var_titleLabel.height = kscale(32)
        var_titleLabel.textAlignment = .center
        var_titleLabel.font = UIFont.systemFont(ofSize: kscale(24), weight: .bold)
        var_titleLabel.textColor = .black
        var_titleLabel.text = "Input password"
        return var_titleLabel
    }()
    
    lazy var var_mobileLabel: UILabel = {
        let var_mobileLabel = UILabel()
        var_mobileLabel.x = kscale(20)
        var_mobileLabel.y = kscale(80)
        var_mobileLabel.width = var_cornerView.width-kscale(40)
        var_mobileLabel.height = kscale(20)
        var_mobileLabel.font = UIFont.systemFont(ofSize: kscale(16), weight: .regular)
        var_mobileLabel.textColor = .black
        var_mobileLabel.text = "+234 " + KAUserManager.shared.user.mobile
        return var_mobileLabel
    }()
    
    lazy var var_pwdView: KAPwdView = {
        var_pwdView = KAPwdView(placeHolder: "Please enter six letters or numbers")
        var_pwdView.x = kscale(20)
        var_pwdView.y = var_mobileLabel.bottom + kscale(16)
        var_pwdView.size = CGSizeMake(var_cornerView.width-kscale(40), kscale(48))
        return var_pwdView
    }()
    
    lazy var var_forgetBtn: UIButton = {
        let var_forgetBtn = UIButton(frame: CGRectMake(var_cornerView.width-kscale(140), var_pwdView.bottom+kscale(12), kscale(120), kscale(15.0)))
        var_forgetBtn.titleLabel?.textAlignment = .right
        var_forgetBtn.setTitle("Forget password", for: .normal)
        var_forgetBtn.setTitleColor(.themeColor, for: .normal)
        var_forgetBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        var_forgetBtn.addTarget(self, action: #selector(ka_forgetButtonClick), for: .touchUpInside)
        return var_forgetBtn
    }()
    
    
    lazy var var_changePhoneBtn: UIButton = {
        let var_changePhoneBtn = UIButton(frame: CGRectMake(kscale(20), var_pwdView.bottom+kscale(12), kscale(160), kscale(15.0)))
        var_changePhoneBtn.titleLabel?.textAlignment = .right
        var_changePhoneBtn.setTitle("Change Phone Number", for: .normal)
        var_changePhoneBtn.setTitleColor(.themeColor, for: .normal)
        var_changePhoneBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        var_changePhoneBtn.addTarget(self, action: #selector(ka_changePhoneBtnClick), for: .touchUpInside)
        return var_changePhoneBtn
    }()
    
    @objc func ka_changePhoneBtnClick() {
        let vc = KAChangeMobileVC()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    lazy var var_signBtn: UIButton = {
        let var_signBtn = UIButton(frame: CGRectMake(kscale(48), var_pwdView.bottom+kscale(60), var_cornerView.width-kscale(96), kscale(50.0)))
        var_signBtn.setTitle("SignUp", for: .normal)
        var_signBtn.setTitleColor(.white, for: .normal)
        var_signBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_signBtn.backgroundColor = .colorBDBDF5
        var_signBtn.layer.cornerRadius = kscale(25)
        var_signBtn.layer.masksToBounds = true
        var_signBtn.addTarget(self, action: #selector(ka_signButtonClick), for: .touchUpInside)
        return var_signBtn
    }()
    
    override func customNavBackAction() {
        for vc in navigationController!.viewControllers {
            if vc.isKind(of: KALoginVC.self) {
                let loginVC = vc as! KALoginVC
                loginVC.var_mobileView.contentTF.text = KAUserManager.shared.user.mobile
                navigationController?.popToViewController(loginVC, animated: true)
                return
            }
        }
        KAVCManager.switchRootVC(false)
    }
    
    lazy var var_pictureView: KAPictureVerifyView = {
        let var_pictureView = KAPictureVerifyView { [self] code, captcheId in
            captchaId = captcheId
            captchaCode = code
            loginService()
        }
        return var_pictureView
    }()
}

extension KAInputPwdVC {
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_setUI()
        ka_bindUI()
    }
    
    func ka_setUI() {
        view.backgroundColor = .colorf2f2f5
        ka_showCustomerNavBar(type: .normal)
        var_navBar.updateUI(alpha: 0)
        
        view.addSubview(var_cornerView)
        var_cornerView.addSubview(var_titleLabel)
        var_cornerView.addSubview(var_mobileLabel)
        var_cornerView.addSubview(var_pwdView)
        var_cornerView.addSubview(var_forgetBtn)
        var_cornerView.addSubview(var_changePhoneBtn)
        var_cornerView.addSubview(var_signBtn)
    }
    
    func ka_bindUI() {
        var_pwdView.contentTF.rx.text
            .orEmpty
            .map { text in
                return (text.count == 4 || text.count == 6) ? .themeColor : .colorBDBDF5
            }
            .bind(to: var_signBtn.rx.backgroundColor)
            .disposed(by: disposeBag)
    }
    
    @objc func ka_forgetButtonClick() {
        let vc = KAVerCodeVC()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func ka_signButtonClick() {
        guard var_pwdView.contentTF.text!.verifyPwd else {
            view.makeToast("Please enter 6 digits or letters"); return
        }
        if (logoutStatus == 15) {
            view.makeToast("This account does not exist"); return
        }
        if (logoutStatus == 29) {
            let message = "This account has been applied for cancellation, and it will take 15 days to complete the cancellation. If you continue to log in now, the application for cancellation of this account will be withdrawn."
            let alert = KAAlertView.alert(withTitle: "Cancel", subtitle: message) { _ in
            }
            alert.addAction(KAAlertAction(title: "Continue login", titleColor: .blue, backgroundColor: .clear) { action in
            })
            alert.addAction(KAAlertAction(title: "I have read and accept", titleColor: .blue, backgroundColor: .clear) { [self] action in
                print("OK button clicked")
                secondLogin = 1
                ka_checkClientId()
            })
            alert.show()
            return
        }
        ka_checkClientId()
    }
    //设备登录校验cliendId接口;校验UUID，判断是否是已注销老用户
    func ka_checkClientId() {
        view.showLoading()
        let paraDic = [
            "mobile":KAUserManager.shared.user.mobile, "cliendId":UIDevice.ka_UUID,
        ]
        loginProvider.request(.checkClientId(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        
                        if isSuccess {
                            guard let content = response?.content else { return }
                            if content.checkResult == 1 {
                                //上个界面校验手机号返回codeToken，如果是空的需要重新调用校验接口；不为空代表手机号校验通过，直接去登录
                                //不为空的情况是从登录页进入该页面；为空是退出登录后直接到了该页面，所以需要重新调校验接口
                                if codeToken.isEmpty {
                                    ka_checkMobile(); return
                                }
                                loginService()
                            } else {
                                //新版添加了图形验证码验证
                                //已经注销的老用户，需要进行短信校验
                                let vc = KAOTPVC()
                                vc.operationType = .OldPhoneLogin
                                vc.mobileCodeToken = codeToken
                                vc.pwd = var_pwdView.contentTF.text!
                                self.navigationController?.pushViewController(vc, animated: true)
                            }
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func ka_checkMobile() {
        NetService.ka_checkMobileWith(mobile: KAUserManager.shared.user.mobile) { [self] isSuccess, message, response in
            if isSuccess {
                guard let user = response?.content else { return }
                let defaultUser = KAUserManager.shared.user
                var newUser = defaultUser.merge(with: user)
                newUser.mobile = KAUserManager.shared.user.mobile
                KAUserManager.shared.user = newUser
                codeToken = user.codeToken
                logoutStatus = user.logoutStatus
                loginService()
            }
        }
    }
    
    func loginService() {
        NetService.ka_loginWith(mobile: KAUserManager.shared.user.mobile, password: var_pwdView.contentTF.text!, codeToken: codeToken, operationType: .nothing, verifyCode: "", verifyToken: "", captchaCode: captchaCode, captchaId: captchaId, secondLogin: secondLogin) { isSuccess, message, response in
            self.captchaId = ""
            self.captchaCode = ""
            if (!isSuccess) {
                guard let status = response?.status else { return }
                if status == 1015 || status == 1016 || status == 1617 || status == 1618 || status == 1619 || status == 1014 || status == 1010 || status == 1017 || status == 7006 || status == 7007 || status == 7008  {
                    self.var_pictureView.show()
                    self.var_pictureView.makeToast(message)
                    return
                }
                self.view.makeToast(message)
                self.var_pictureView.dismiss()
            } else {
                self.var_pictureView.dismiss()
            }
        }
    }
}
